package cn.wolfcode.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 生产者与消费者
 */
public class ProuctAndConsumerLockDemo {
    public static void main(String[] args) {
        ClerkLockDemo clerk = new ClerkLockDemo();
        new Thread(new ProductDemo(clerk),"生产者A").start();
        new Thread(new ProductDemo(clerk),"生产者B").start();
        new Thread(new ConsumerLockDemo(clerk),"消费者A").start();
        new Thread(new ConsumerLockDemo(clerk),"消费者B").start();
    }

}

class ClerkLockDemo {
    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    private  int product = 0;
    public void product(){
        lock.lock();
        try {
            while (product>=1){
                System.out.println("仓库已经满了");
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName()+ ++product);
            condition.signalAll();
        }finally {
            lock.unlock();
        }
    }

    public synchronized void  sale(){
        lock.lock();
        try {
            while (product<=0){
                System.out.println("缺货");
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName()+ --product);
            condition.signalAll();
        }finally {
            lock.unlock();
        }
    }
}

class ProductDemo implements Runnable{
    ClerkLockDemo clerk;
    public ProductDemo(ClerkLockDemo clerk){
        this.clerk = clerk;
    }
    public void run() {
        for (int i = 0; i <20 ; i++) {
            clerk.product();

        }
    }
}

class ConsumerLockDemo implements Runnable{
    ClerkLockDemo clerk;
    public ConsumerLockDemo(ClerkLockDemo clerk){
        this.clerk = clerk;
    }
    public void run() {
        for (int i = 0; i <20 ; i++) {
            clerk.sale();

        }
    }
}
